package org.realogic.cfm.persistence.dialect;

import java.util.List;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.realogic.cfm.persistence.KParameter;
import org.realogic.cfm.persistence.query.QueryCondition;

/**
 * 仿照hibernate的Dialect
 * 
 */
public abstract class AbstractDialect implements Dialect {

	public String getCountSQL(String sql) {
		String rSql = sql.trim();
		String tmpSql = sql.trim().toLowerCase();
		if (tmpSql.indexOf("group by") != -1 || tmpSql.indexOf(" distinct ") != -1) {
			return getSelectCountSQL4GroupBy(sql);
		}
		String tSql = "select count(*) as totalsize from ";
		String from = null;
		String where = null;
		int indexFrom = tmpSql.indexOf("from ");
		int indexWhere = tmpSql.indexOf("where ");
		int indexOrder = tmpSql.indexOf("order by ");
		if (indexWhere > -1) {
			from = rSql.substring(indexFrom + 5, indexWhere);
			if (indexOrder > -1) {
				where = rSql.substring(indexWhere + 6, indexOrder);
			} else {
				where = rSql.substring(indexWhere + 6);
			}
		} else {
			if (indexOrder > -1) {
				from = rSql.substring(indexFrom + 5, indexOrder);
			} else {
				from = rSql.substring(indexFrom + 5);
			}
		}
		tSql += from;
		if (where != null) {
			tSql = tSql + " where " + where;
		}
		return tSql;
	}
	
	public String getSelectCountSQL4GroupBy(String sql) {
		return "select count(1) from (" + sql + ")";
	}

	public List<ParameterMapping> newParameterMappings(MappedStatement mappedStatement, BoundSql boundSql, QueryCondition queryCondition, boolean isForPage) {
		throw new UnsupportedOperationException("paged queries not supported");
	}
	
	public List<KParameter> newDivPageParameters(List<KParameter> paramters) {
		// TODO 需要进一步实现
		return paramters;
	}
}
